<template>
  <div class="teacher-list-container" style="width: 100% !important; margin: 0 !important; padding: 0 !important; position: absolute; top: 0; left: 0; right: 0; bottom: 0;">
    <!-- 管理员控制台头部 -->
    <el-header class="admin-header">
      <div class="header-left">
        <h1>在线考试系统管理控制台</h1>
      </div>
      <div class="header-right">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-icon><UserFilled /></el-icon>
            <span class="username">{{ userInfo.username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleChangePassword">修改密码</el-dropdown-item>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <el-card class="teacher-card" style="border-radius: 0;">
      <template #header>
        <div class="card-header">
          <h2>教师管理</h2>
        </div>
      </template>
      <div class="search-bar" style="padding: 10px 10px 20px 10px !important; margin: 0 !important;">
        <el-input v-model="searchQuery" placeholder="搜索教师姓名/编号" prefix-icon="Search"
          style="width: 300px; margin-right: 10px;" />
        <el-button type="primary" @click="handleAddTeacher">添加教师</el-button>
      </div>
      <!-- 添加表格包装器以支持水平滚动 -->
      <div class="table-wrapper">
        <el-table v-loading="loading" :data="filteredTeachers" style="width: 100%">
          <el-table-column prop="teacherId" label="教师ID" width="80"></el-table-column>
          <el-table-column prop="teacherNo" label="教师编号" width="120"></el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="title" label="职称" width="100"></el-table-column>
          <el-table-column prop="department" label="所属部门" width="150"></el-table-column>
          <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }"> {{ formatDate(row.createTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEditTeacher(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteTeacher(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination" style="padding: 20px 10px !important; margin: 0 !important; justify-content: flex-end;">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          :total="teachers.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 编辑教师对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑教师" width="600px" :close-on-click-modal="false">
      <el-form :model="teacherForm" :rules="rules" ref="teacherFormRef" label-width="120px">
        <el-form-item label="教师编号" prop="teacherNo">
          <el-input v-model="teacherForm.teacherNo" placeholder="请输入教师编号" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="teacherForm.title" placeholder="请输入职称（如：讲师、教授）" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="teacherForm.department" placeholder="请输入所属部门" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, postForm, postJson } from '../../utils/api'
import { UserFilled, ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()

const userInfo = ref({
  username: '',
  roleName: ''
})

onMounted(() => {
  // 从本地存储获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
})

const handleLogout = async () => {
  try {
    // 调用后端登出接口，带上cookie
    await get('/user/logout')
    
    // 清除本地存储的用户信息
    localStorage.removeItem('user')
    
    // 跳转到登录页面
    router.push('/login')
    
    ElMessage.success('退出登录成功')
  } catch (error) {
    console.error('退出登录失败:', error)
    // 即使后端调用失败，也要清除本地状态并跳转
    localStorage.removeItem('user')
    router.push('/login')
    ElMessage.success('退出登录成功')
  }
}

const handleChangePassword = () => {
  router.push('/admin/change-password')
}

// 教师数据
const teachers = ref<any[]>([])
const loading = ref(false)
const searchQuery = ref('')

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 过滤后的教师列表
const filteredTeachers = computed(() => {
    let result = teachers.value
    
    // 搜索过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter(teacher => 
        teacher.teacherNo?.toLowerCase().includes(query) ||
        teacher.username?.toLowerCase().includes(query) ||
        teacher.realName?.toLowerCase().includes(query) ||
        teacher.department?.toLowerCase().includes(query)
      )
    }
    
    // 分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    return result.slice(start, end)
  })

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 加载教师列表
const loadTeachers = async () => {
  loading.value = true
  try {
    // 调用后端API获取教师列表
    const result = await get('/teacher/query')
    
    // 根据后端返回的数据格式处理
    if (result.code === 200) {
      // 适配/teacher/query的返回格式
      teachers.value = result.data || []
      // 更新分页总数
      pagination.total = result.dataCount || teachers.value.length
    } else {
      ElMessage.error(result.msg || '加载教师列表失败')
    }
  } catch (error) {
    console.error('加载教师列表失败:', error)
    ElMessage.error('网络错误，请检查后端服务是否正常运行')
  } finally {
    loading.value = false
  }
}

// 添加教师
const handleAddTeacher = () => {
  router.push('/admin/teacher/add')
}

// 编辑教师对话框状态
const dialogVisible = ref(false)
const teacherFormRef = ref<FormInstance>()

// 编辑教师表单数据
const teacherForm = reactive({
  teacherId: '',
  userId: '',
  teacherNo: '',
  title: '',
  department: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  teacherNo: [
    { message: '请输入教师编号', trigger: 'blur' }
  ],
  title: [
    { message: '请输入职称', trigger: 'blur' }
  ],
  department: [
    { message: '请输入所属部门', trigger: 'blur' }
  ]
})

// 编辑教师
const handleEditTeacher = (teacher: any) => {
  // 填充表单数据，只包含后端要求的字段
  teacherForm.teacherId = teacher.teacherId
  teacherForm.userId = teacher.userId || ''
  teacherForm.teacherNo = teacher.teacherNo || ''
  teacherForm.title = teacher.title || ''
  teacherForm.department = teacher.department || ''
  
  // 显示对话框
  dialogVisible.value = true
}

// 提交编辑表单
const submitForm = async () => {
  if (!teacherFormRef.value) return
  
  try {
    await teacherFormRef.value.validate()
    
    // 准备提交数据，不包含roleId，由后端处理默认值
    const submitData = { ...teacherForm }
    
    // 调用后端API更新教师信息
    const result = await postJson('/teacher/update', submitData)
    
    if (result.code === 200) {
      ElMessage.success('编辑成功')
      dialogVisible.value = false
      // 重新加载教师列表
      loadTeachers()
    } else {
      ElMessage.error(result.msg || '编辑失败')
    }
  } catch (error: any) {
    // 表单验证失败或网络错误
    if (error !== 'cancel') {
      console.error('编辑教师失败:', error)
      if (!error.message?.includes('validation')) {
        ElMessage.error('网络错误，请检查后端服务是否正常运行')
      }
    }
  }
}

// 删除教师
const handleDeleteTeacher = async (teacher: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教师「${teacher.realName}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除教师
    const result = await get(`/teacher/delete?id=${teacher.teacherId}`)
    
    if (result.code === 200) {
      // 从列表中移除删除的教师
      teachers.value = teachers.value.filter(t => t.teacherId !== teacher.teacherId)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error: any) {
    // 用户取消删除或发生错误
    if (error !== 'cancel') {
      console.error('删除教师失败:', error)
      ElMessage.error('网络错误，请检查后端服务是否正常运行')
    }
  }
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
}

// 当前页码变更
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
}

// 页面加载时获取教师列表
onMounted(() => {
  loadTeachers()
})
</script>

<style scoped>
.admin-header {
  background-color: #1890ff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h1 {
  font-size: 20px;
  margin: 0;
  font-weight: normal;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: white;
}

.username {
  margin: 0 8px;
}

/* 重置样式并确保容器填满整个屏幕 */
:deep(.el-card) {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  border-radius: 0;
  border: none;
  padding: 0 !important;
  /* 左贴合 */
}

/* 移除卡片头部和内容区域的默认内边距 */
:deep(.el-card__header) {
  padding: 0 !important;
  margin: 0 !important;
  border-bottom: none;
}

:deep(.el-card__body) {
  padding: 0 !important;
  margin: 0 !important;
  overflow: hidden;
}

/* 外层容器完全填充满屏幕 */
.teacher-list-container {
    padding: 0 !important;
    min-height: 100vh;
    height: 100vh;
    background-color: #f5f5f5;
    width: 100% !important;
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    overflow: hidden;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    border-radius: 0 !important;
  }

/* 卡片样式 - 完全消除内外边距和圆角 */
  .teacher-card {
    width: 100% !important;
    max-width: none !important;
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
    box-shadow: none !important;
    background-color: #fff;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    /* border-radius: 0 !important; */
  }

/* 头部样式 */
.card-header {
  padding: 10px 10px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 0;
  width: 100% !important;
}

.card-header h2 {
  margin: 0 !important;
  font-size: 18px;
  font-weight: bold;
  padding: 0 !important;
}

/* 搜索栏样式 */
.search-bar {
    padding: 10px 0 20px 0;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    min-width: 100%;
    width: 100%;
    margin: 0;
    /* 确保搜索栏最小宽度 */
  }

/* 表格容器样式 - 关键修改：添加水平滚动和最小宽度 */
.table-wrapper {
    flex: 1;
    overflow-x: auto;
    /* 允许水平滚动 */
    overflow-y: auto;
    /* 允许垂直滚动 */
    min-width: 100%;
    width: 100%;
    /* 确保表格有足够宽的最小宽度 */
    padding: 0;
    margin: 0;
  }

:deep(.el-table) {
    width: 100%;
    min-width: 100%;
    /* 确保表格有足够宽的最小宽度 */
  }

/* 强制表格列使用指定宽度 */
:deep(.el-table th) {
  white-space: nowrap;
  /* 防止表头文字换行 */
  font-size: 14px;
  /* 调整表头字体大小 */
  padding: 12px 8px;
  /* 调整表头内边距 */
}

:deep(.el-table td) {
  font-size: 13px;
  /* 调整表格内容字体大小 */
  padding: 12px 8px;
  /* 调整表格内容内边距 */
}

/* 分页样式 */
.pagination {
    padding: 20px 0;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    min-width: 100%;
    width: 100%;
    margin: 0;
    /* 确保分页栏最小宽度 */
  }

/* 响应式调整 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-bar .el-input,
  .search-bar .el-button {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }

  .pagination {
    justify-content: center;
  }
}
</style>

/* 全局样式重置，确保整个页面背景一致 */
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  width: 100% !important;
  height: 100% !important;
  background-color: #f5f5f5 !important;
  overflow: hidden;
}

#app {
  width: 100% !important;
  height: 100% !important;
  background-color: #f5f5f5 !important;
}
</style>